package com.lzq.course.server.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzq.course.server.domain.RoleUser;
import com.lzq.course.server.domain.RoleUserExample;
import com.lzq.course.server.dto.RoleUserDto;
import com.lzq.course.server.dto.PageDto;
import com.lzq.course.server.mapper.RoleUserMapper;
import com.lzq.course.server.util.CopyUtil;
import com.lzq.course.server.util.UuidUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class RoleUserService {

    @Resource
    private RoleUserMapper roleUserMapper;

    /**
     * example 这个文件很有用
     * 可以帮我们生成where order 查询
     * 不用单独写sql的增删改查
     */
    public void list(PageDto<RoleUserDto> pageDto) {
        // 分页查询 页码不是从0开始
        PageHelper.startPage(pageDto.getPage(), pageDto.getSize());

        // 排序
        RoleUserExample roleUserExample = new RoleUserExample();

        // 查询
        List<RoleUser> roleUserList = roleUserMapper.selectByExample(roleUserExample);

        PageInfo<RoleUser> pageInfo = new PageInfo<>(roleUserList);
        pageDto.setTotal(pageInfo.getTotal());

        List<RoleUserDto> roleUserDtoList = CopyUtil.copyList(roleUserList, RoleUserDto.class);

        pageDto.setList(roleUserDtoList);
    }

    /**
     * 保存 修改
     * @param roleUserDto
     */
    public void save(RoleUserDto roleUserDto) {
        //BeanUtils.copyProperties(roleUserDto, roleUser);
        RoleUser copyRoleUser = CopyUtil.copy(roleUserDto, RoleUser.class);

        if (StringUtils.isEmpty(roleUserDto.getId())) {
            // 新增
            // 八位的 id
            copyRoleUser.setId(UuidUtil.getShortUuid());

            Date now = new Date();

            roleUserMapper.insert(copyRoleUser);
        } else {
            // 编辑
            roleUserMapper.updateByPrimaryKey(copyRoleUser);
        }
    }

    /**
     * 删除
     * @param id
     */
    public void delete(String id) {
        roleUserMapper.deleteByPrimaryKey(id);
    }
}
